package com.example.venue_reservation_service.service.impl;

import com.alibaba.druid.sql.ast.expr.SQLAggregateExpr;
import com.alibaba.druid.sql.ast.expr.SQLAggregateOption;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.venue_reservation_service.domain.Payment;
import com.example.venue_reservation_service.domain.VenueSlot;
import com.example.venue_reservation_service.dto.HotDTO;
import com.example.venue_reservation_service.dto.PageDTO;
import com.example.venue_reservation_service.mapper.PaymentMapper;
import com.example.venue_reservation_service.mapper.VenueHotMapper;
import com.example.venue_reservation_service.service.PaymentService;
import com.example.venue_reservation_service.service.VenueHotService;
import com.example.venue_reservation_service.domain.VenueHot;
import com.example.venue_reservation_service.utils.MinioUtil;
import com.example.venue_reservation_service.vo.QueryVO;
import com.example.venue_reservation_service.vo.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
* @author 31586
* @description 针对表【venue_hot(热点时间表)】的数据库操作Service实现
* @createDate 2024-11-29 20:21:26
*/
@Service
public class VenueHotServiceImpl extends ServiceImpl<VenueHotMapper, VenueHot>
    implements VenueHotService {

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private PaymentMapper paymentMapper;

    @Value("${access.url}")
    private String imgPrefix;

    @Override
    public Result getHots(PageDTO dto) {
        Page<VenueHot> page = new Page<>(dto.getCurrent(), dto.getSize());
        page = page(page, null);
        QueryVO<VenueHot> vo = new QueryVO<>();
        List<VenueHot> records = page.getRecords();
        records.forEach(item ->{
            if(StringUtils.isNotBlank(item.getImgUrl())){
                item.setImgUrl(imgPrefix + item.getImgUrl());
            }
        });
        vo.setList(records);
        vo.setTotal(page.getTotal());
        return Result.ok(vo).message("查询成功");
    }

    @Override
    public Result addHot(HotDTO dto) {
        // 查找有无相似内容
        String trim = dto.getDescription().trim(); // 去除空格效果
        int size = list(Wrappers.<VenueHot>lambdaQuery().like(VenueHot::getDescription, trim)).size();
        if(size > 0){
            return Result.fail().message("存在相似内容");
        }
        VenueHot hot = new VenueHot();
        hot.setDescription(trim);
        hot.setAddTime(LocalDateTime.now());
        save(hot);
        return Result.ok().message("ok");
    }

    @Override
    public Result updateHot(HotDTO dto) {
        VenueHot hot = getById(dto.getId());
        if (Optional.ofNullable(hot).isEmpty()) {
            return Result.fail().message("未查询到相关信息");
        }
        hot.setDescription(dto.getDescription().trim());
        hot.setAddTime(LocalDateTime.now());
        updateById(hot);
        return Result.ok().message("ok");
    }

    @Override
    public Result uploadImg(MultipartFile file, Integer id) {
        VenueHot hot = getById(id);
        if (Optional.ofNullable(hot).isEmpty()) {
            return Result.fail().message("未加载到相关信息");
        }
        String imgUrl = hot.getImgUrl();
        try{
            if (StringUtils.isNotBlank(imgUrl)) {
                minioUtil.removeFile(imgUrl);
            }
            String[] split = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");

            String filename = System.currentTimeMillis() + "-" + id + "." +split[split.length - 1] ;
            minioUtil.uploadFile(file, filename, file.getContentType());

            hot.setImgUrl(filename);
            updateById(hot);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail().message("修改失败");
        }
        return Result.ok().message("ok");
    }

    @Override
    public Result removeHot(Integer id) {
        VenueHot hot = getById(id);
        if (Optional.ofNullable(hot).isEmpty()) {
            return Result.fail().message("未加载到相关信息");
        }
        String imgUrl = hot.getImgUrl();
        try{
            if (StringUtils.isNotBlank(imgUrl)) {
                minioUtil.removeFile(imgUrl);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail().message("图片删除失败");
        }
        removeById(id);
        return Result.ok().message("ok");
    }

    @Override
    public Result getMoney() {
        LocalDateTime zero = LocalDateTime.now().with(LocalTime.MIN);
        QueryWrapper<Payment> queryWrapper = Wrappers.query();
        queryWrapper.select("SUM(amount) as total_salary")
                .between("time", zero, zero.plusDays(1L))
                .in("situation", "账户余额充值", "支出" );
        List<Map<String, Object>> maps = paymentMapper.selectMaps(queryWrapper);

        double total_salary = (maps.get(0) == null )? 0.0 : Double.parseDouble(maps.get(0).get("total_salary") + "");
        return Result.ok(total_salary).message("ok");
    }
}




